const fs = require("fs")
const net = require("net")
const express = require("express")
const open = require("opn")
const sha256 = require('js-sha256')
const { exit, config } = require("process")
const path = require('path')
const app = express();
const axios = require('axios')
console.clear()

function postToServer(content) {
  return new Promise(async (resolve, reject) => {
    let re = JSON.parse(await readFile("./config.JSON"))
  let port1 = re.port
    var data = content;
    var config = {
       method: 'post',
       url: 'http://127.0.0.1:' + port1.toString() + '/api/configure',
       headers: { 
          'Content-Type': 'text/plain', 
          'Accept': '*/*', 
          'Connection': 'keep-alive'
       },
       data : data
    };
    axios(config)
    .then((response) => {
       return resolve(response)
    }).catch(error=>{
      console.log(error)
    })
  });
}

let port = 0

async function main(){
    port = await findFreePort()
    app.listen(port, () => {
      console.log(`The FileDB Configure user interface has been opened in the browser.\nIf the browser is not launched, please open the browser and visit http://127.0.0.1:` + port.toString() + `.`);
      open("http://127.0.0.1:" + port.toString())
    });
}

app.get("/changeUserPassword/:userName/:orp/:np",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByUsername',
    userName:req.params.userName
  }))
  let re = JSON.parse(await readFile("./db/userConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i].name==req.params.userName){
      if(re[i].password != sha256(req.params.orp)){
        res.send({
          status:0,
          content:'Incorrect password'
        })
        return
      }
      re[i].password = sha256(req.params.np)
      await updateFileContent("./db/userConfig",JSON.stringify(re))
      res.send({
        status:1,
        content:'Success'
      })
      return
    }
  }
  res.send({
    status:0,
    content:'User does not exist'
  })
})

app.get("/deleteTable/:userName/:databaseName/:tableName/:password",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByDatabasename',
    databaseName:req.params.databaseName
  }))
  let re = JSON.parse(await readFile("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i].name==req.params.tableName){
      re = arrayDeleteElem(re,i)
      break
    }
  }
  await updateFileContent("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig",JSON.stringify(re))
  res.send({
    status:1
  })
})

app.get("/moveCol/:userName/:databaseName/:tableName/:colName/:op/:password",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByDatabasename',
    databaseName:req.params.databaseName
  }))
  let re = JSON.parse(await readFile("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i].name == req.params.tableName){
      let cc = {}
      let keys = Object.keys(re[i].columns)
      for(let i1=0;i1<keys.length;i1++){
        if(keys[i1]==req.params.colName){
          if(req.params.op=='up'){
            let t = keys[i1-1]
            keys[i1-1] = keys[i1]
            keys[i1] = t
          }else{
            let t = keys[i1+1]
            keys[i1+1] = keys[i1]
            keys[i1] = t
            i1+=1
          }
        }
      }
      for(let i1=0;i1<keys.length;i1++){
        cc[keys[i1]] = re[i].columns[keys[i1]]
      }
      re[i].columns = cc
      break
    }
  }
  let re1 = await postToServer(JSON.stringify({
    opName:'moveCol',
    user:req.params.userName,
    database:req.params.databaseName,
    table:req.params.tableName,
    colName:req.params.colName,
    op:req.params.op,
    password:req.params.password
  }))
  if(re1.status==0){
    res.send({
      stauts:0,
      content:re1.content
    })
    return
  }
  await updateFileContent("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig",JSON.stringify(re))
  res.send({
    status:1
  })
})

app.get("/deleteCol/:userName/:databaseName/:tableName/:colName/:password",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByDatabasename',
    databaseName:req.params.databaseName
  }))
  let re = JSON.parse(await readFile("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i].name == req.params.tableName){
      delete re[i].columns[req.params.colName]
      break
    }
  }
  let re1 = await postToServer(JSON.stringify({
    opName:'deleteCol',
    user:req.params.userName,
    database:req.params.databaseName,
    table:req.params.tableName,
    colName:req.params.colName,
    password:req.params.password
  }))
  if(re1.status==0){
    res.send({
      stauts:0,
      content:re1.content
    })
    return
  }
  await updateFileContent("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig",JSON.stringify(re))
  res.send({
    stauts:1
  })
})

app.get("/changeColType/:userName/:databaseName/:tableName/:colName/:colType/:password",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByDatabasename',
    databaseName:req.params.databaseName
  }))
  let re = JSON.parse(await readFile("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i].name == req.params.tableName){
      for(let i1=0;i1<Object.keys(re[i].columns).length;i1++){
        if(Object.keys(re[i].columns)[i1]==req.params.colName){
          re[i].columns[Object.keys(re[i].columns)[i1]] = req.params.colType
          break
        }
      }
      break
    }
  }
  let re1 = await postToServer(JSON.stringify({
    opName:'tableChangeColType',
    user:req.params.userName,
    database:req.params.databaseName,
    table:req.params.tableName,
    colName:req.params.colName,
    colType:req.params.colType,
    password:req.params.password
  }))
  if(re1.status==0){
    res.send({
      stauts:0,
      content:re1.content
    })
    return
  }
  await updateFileContent("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig",JSON.stringify(re))
  res.send({
    stauts:1
  })
})

app.get("/changeColName/:userName/:databaseName/:tableName/:colName/:newColName",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByDatabasename',
    databaseName:req.params.databaseName
  }))
  let re = JSON.parse(await readFile("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i].name==req.params.tableName){
      for(let i1=0;i1<Object.keys(re[i].columns).length;i1++){
        if(Object.keys(re[i].columns)[i1]==req.params.newColName){
          res.send({
            status:0,
            content:'Column already exists'
          })
          return
        }
      }
      let t = {}
      for(let i1=0;i1<Object.keys(re[i].columns).length;i1++){
        if(Object.keys(re[i].columns)[i1]==req.params.colName){
          t[req.params.newColName] = re[i].columns[Object.keys(re[i].columns)[i1]]
        }else{
          t[Object.keys(re[i].columns)[i1]] = re[i].columns[Object.keys(re[i].columns)[i1]]
        }
      }
      re[i].columns = t
      break
    }
  }
  await updateFileContent("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig",JSON.stringify(re))
  res.send({
    status:1
  })
})

app.get("/addCol/:userName/:databaseName/:tableName/:colName/:colType/:password",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByDatabasename',
    databaseName:req.params.databaseName
  }))
  let re = JSON.parse(await readFile("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i].name==req.params.tableName){
      for(let i1=0;i1<Object.keys(re[i].columns).length;i1++){
        if(Object.keys(re[i].columns)[i1]==req.params.colName){
          res.send({
            status:0,
            content:'The column already exists'
          })
          return
        }
      }
      re[i]['columns'][req.params.colName] = req.params.colType
      break
    }
  }
  await postToServer(JSON.stringify({
    opName:'tableAddCol',
    user:req.params.userName,
    database:req.params.databaseName,
    table:req.params.tableName,
    colName:req.params.colName,
    colType:req.params.colType,
    password:req.params.password
  }))
  await updateFileContent("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig",JSON.stringify(re))
  res.send({
    status:1
  })
})

app.get("/changeTableName/:userName/:databaseName/:tableName/:newTableName",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByDatabasename',
    databaseName:req.params.databaseName
  }))
  let re = JSON.parse(await readFile("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i].name==req.params.newTableName){
      res.send({
        status:0,
        content:'The table already exists.'
      })
      return
    }
  }
  for(let i=0;i<re.length;i++){
    if(re[i].name==req.params.tableName){
      re[i].name = req.params.newTableName
      break
    }
  }
  await renameFile("./db/" + req.params.userName + "/" + req.params.databaseName + "/" + req.params.tableName,req.params.newTableName)
  await updateFileContent("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig",JSON.stringify(re))
  res.send({
    status:1
  })
})

app.get("/changeDatabase/:userName/:databaseName/:newDatabaseName",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByDatabasename',
    databaseName:req.params.databaseName
  }))
  let re = JSON.parse(await readFile("./db/" + req.params.userName + "/databaseConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i]==req.params.newDatabaseName){
      res.send({
        status:0,
        content:'Database already exists'
      })
      return
    }
  }
  for(let i=0;i<re.length;i++){
    if(re[i]==req.params.databaseName){
      re[i] = req.params.newDatabaseName
      break
    }
  }
  await renameFolder("./db/" + req.params.userName + "/" + req.params.databaseName,req.params.newDatabaseName)
  await updateFileContent("./db/" + req.params.userName + "/databaseConfig",JSON.stringify(re))
  res.send({
    status:1
  })
})

app.get("/changeUser/:userName/:newUserName",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByUsername',
    userName:req.params.userName
  }))
  let re = JSON.parse(await readFile("./db/userConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i].name==req.params.newUserName){
      res.send({
        status:0,
        content:'User already exists'
      })
      return
    }
  }
  for(let i=0;i<re.length;i++){
    if(re[i].name==req.params.userName){
      re[i].name=req.params.newUserName
      break
    }
  }
  await renameFolder("./db/" + req.params.userName,req.params.newUserName)
  await updateFileContent("./db/userConfig",JSON.stringify(re))
  res.send({
    status:1
  })
})

app.get("/addTable/:userName/:databaseName/:tableName",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByDatabasename',
    databaseName:req.params.databaseName
  }))
  let re = JSON.parse(await readFile("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i].name==req.params.tableName){
      res.send({
        status:0,
        content:'The table already exists'
      })
      return
    }
  }
  re.push({
    name:req.params.tableName,
    columns:{
      mark:'string'
    }
  })
  await updateFileContent("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig",JSON.stringify(re))
  await createFileWithContent("./db/" + req.params.userName + "/" + req.params.databaseName + "/" + req.params.tableName,"")
  res.send({
    status:1
  })
})

app.get("/deleteDatabase/:userName/:databaseName",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByDatabasename',
    databaseName:req.params.databaseName
  }))
  let re = JSON.parse(await readFile("./db/" + req.params.userName + "/databaseConfig"))
  let re0 = []
  for(let i=0;i<re.length;i++){
    if(re[i]==req.params.databaseName){
      continue
    }
    re0.push(re[i])
  }
  await deleteFolder("./db/" + req.params.userName + "/" + req.params.databaseName)
  await updateFileContent("./db/" + req.params.userName + "/databaseConfig",JSON.stringify(re0))
  res.send({
    status:1
  })
})

app.get("/addDatabase/:userName/:databaseName",async (req,res)=>{
  let re = JSON.parse(await readFile("./db/" + req.params.userName + "/databaseConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i]==req.params.databaseName){
      res.send({
        status:0,
        content:'Database already exists'
      })
      return
    }
  }
  re.push(req.params.databaseName)
  await createFolder("./db/" + req.params.userName + "/" + req.params.databaseName)
  await createFileWithContent("./db/" + req.params.userName + "/" + req.params.databaseName + "/tableConfig","[]")
  await updateFileContent("./db/" + req.params.userName + "/databaseConfig",JSON.stringify(re))
  res.send({
    status:1
  })
})

app.get("/deleteUser/:userName",async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service not running'
    })
    return
  }
  await postToServer(JSON.stringify({
    opName:'unloadDatabaseByUsername',
    userName:req.params.userName
  }))
  let re = JSON.parse(await readFile("./db/userConfig"))
  let re0 = []
  for(let i=0;i<re.length;i++){
    if(re[i].name==req.params.userName){
      continue
    }
    re0.push(re[i])
  }
  await deleteFolder("./db/" + req.params.userName)
  await updateFileContent("./db/userConfig",JSON.stringify(re0))
  res.send({
    status:1
  })
})

app.get('/addUser/:userName/:userPassword',async (req,res)=>{
  let re = JSON.parse(await readFile("./db/userConfig"))
  for(let i=0;i<re.length;i++){
    if(re[i].name==req.params.userName){
      res.send({
        status:0,
        content:'User already exists'
      })
      return
    }
  }
  re.push({
    name:req.params.userName,
    password:sha256(req.params.userPassword)
  })
  await createFolder("./db/" + req.params.userName)
  await createFileWithContent("./db/" + req.params.userName + "/databaseConfig","[]")
  await updateFileContent("./db/userConfig",JSON.stringify(re))
  res.send({
    status:1
  })
})

app.get('/tableList/:user/:database',async (req,res)=>{
  let re = await readFile("./db/" + req.params.user + "/" + req.params.database + "/tableConfig")
  res.send({
    status:1,
    results:re
  })
})

async function checkFileDBService(){
  let re = JSON.parse(await readFile("./config.JSON"))
  let port = re.port
  let rea = ''
  try {
    rea = await axios.get("http://127.0.0.1:" + port.toString() + "/")
  } catch (error) {
    console.log(error)
    return false
  }
  return true
}

app.get('/loginUser/:user/:password',async (req,res)=>{
  if((await checkFileDBService())==false){
    res.send({
      status:0,
      content:'FileDB service is not running'
    })
    return
  }
  let user = req.params.user
  let password = sha256(req.params.password)
  let users = JSON.parse(await readFile("./db/userConfig"))
  for(let i=0;i<users.length;i++){
    if(users[i].name==user){
      if(users[i].password==password){
        let databases = JSON.parse(await readFile("./db/" + user + "/databaseConfig"))
        res.send({
          status:1,
          content:'Success',
          results:databases
        })
        return
      }else{
        res.send({
          status:0,
          content:'Incorrect password'
        })
        return
      }
    }
  }
  res.send({
    status:0,
    content:'User does not exist'
  })
  return
})

app.get('/userList',async (req,res)=>{
  let users = JSON.parse(await readFile("./db/userConfig"))
  let re = []
  for(let i=0;i<users.length;i++){
    re.push(users[i].name)
  }
  res.send({
    status:true,
    results:re
  })
})

app.get('/addUser/:data',async (req,res)=>{
  let data = JSON.parse(req.params.data)
  data.password = sha256(data.password)
  if((await checkPathExists("./db"))==false){
    await createFolder("db")
  }
  if((await checkPathExists("./db/userConfig"))==false){
    await createFileWithContent("./db/userConfig",JSON.stringify([]))
  }
  let ucd = JSON.parse(await readFile('./db/userConfig'))
  for(let i=0;i<ucd.length;i++){
    if(ucd[i].name==data.name){
      res.send({
        status:false,
        content:'User already exists'
      })
      return
    }
  }
  ucd.push({
    name:data.name,
    password:data.password
  })
  await updateFileContent("./db/userConfig",JSON.stringify(ucd))
  await createFolder("./db/" + data.name)
  await createFileWithContent("./db/" + data.name + "/databaseConfig",JSON.stringify([]))
  res.send({
    status:true
  })
  return
})

app.get('/modifyPort/:port',async (req,res)=>{
  if(checkPathExists("./config.JSON")==false){
    let configJSONContent = await readFile('./config.JSON')
    configJSONContent = JSON.parse(configJSONContent)
    configJSONContent.port = parseInt(req.params.port)
    createFileWithContent("config.JSON",JSON.stringify({
      port:parseInt(req.params.port)
    }))
  }else{
    updateFileContent("config.JSON",JSON.stringify({
      port:parseInt(req.params.port)
    }))
  }
  res.send({
    status:true
  })
})

app.get('/portInUseState/:port',async (req,res)=>{
  res.send({
    status:await isPortTaken(parseInt(req.params.port))
  })
})

app.get('/page/:pageName',async (req,res)=>{
  let pageHTML = await readFile("./ConfigureUI/" + req.params.pageName + ".html")
  res.send(pageHTML);
})

app.get('/', async (req, res) => {
    let homeHTML = await readFile("./ConfigureUI/home.html")
    res.send(homeHTML);
});

app.get("/initializationState",async (req,res)=>{
  if((await checkPathExists("./db"))==false){
    res.send({
      status:false
    })
    return
  }
  if((await checkPathExists("./db/userConfig"))==false){
    res.send({
      status:false
    })
    return
  }
  res.send({
    status:true
  })
  return
})

app.get('/exit', (req, res) => {
    res.send()
    exit(0)
});

main()

function checkPathExists(fileOrFolderPath) {
  return new Promise((resolve) => {
    fs.access(fileOrFolderPath, fs.constants.F_OK, (err) => {
      if (err) {
        return resolve(false);
      } else {
        return resolve(true);
      }
    });
  });
}

async function waitSeconds(n){
  return new Promise((resolve, reject) => {
    setTimeout(()=>{
      return resolve()
    },n*1000)
  });
}

function print(string){
    console.log(string.toString())
}

function findFreePort() {
  return new Promise((resolve, reject) => {
    const startPort = 30000
    const endPort = 50000
    const portRange = endPort - startPort + 1;
    const portAttempts = Array.from({ length: portRange }, (_, index) => startPort + index);
    function tryPort(port) {
      const server = net.createServer();
      server.listen(port, () => {
        server.once('close', () => {
          resolve(port);
        });
        server.close();
      });
      server.on('error', () => {
        if (portAttempts.length > 0) {
          tryPort(portAttempts.shift());
        } else {
          reject(new Error('No free ports available'));
        }
      });
    }
    tryPort(startPort);
  });
}

function isPortTaken(port) {
  return new Promise((resolve, reject) => {
      const server = net.createServer()
          .listen(port)
          .on('listening', () => {
              server.close();
              resolve(true);
          })
          .on('error', (err) => {
              if (err.code === 'EADDRINUSE') {
                  resolve(false);
              } else {
                  reject(err);
              }
          });
  });
}

function createFolder(folderName) {
  return new Promise((resolve, reject) => {
    const folderPath = path.join(__dirname, folderName);

    fs.mkdir(folderPath, { recursive: true }, (err) => {
      if (err) {
        reject(err);
      } else {
        return resolve();
      }
    });
  });
}

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) {
        reject(err)
      } else {
        return resolve(data)
      }
    })
  })
}

function createFileWithContent(filePath, content) {
  return new Promise((resolve, reject) => {
    fs.writeFile(filePath, content, { flag: 'wx' }, (err) => {
      if (err) {
        reject(err);
      } else {
        return resolve();
      }
    });
  });
}

function checkPathExists(fileOrFolderPath) {
  return new Promise((resolve) => {
    fs.access(fileOrFolderPath, fs.constants.F_OK, (err) => {
      if (err) {
        return resolve(false);
      } else {
        return resolve(true);
      }
    });
  });
}

function updateFileContent(filePath, content) {
  return new Promise((resolve, reject) => {
    fs.unlink(filePath, (error) => {
      if (error && error.code !== 'ENOENT') {
        reject(error);
      } else {
        fs.writeFile(filePath, content, { flag: 'w+' }, (error) => {
          if (error) {
            reject(error);
          } else {
            resolve();
          }
        });
      }
    });
  });
}

function getDirectoriesInFolder(folderPath) {
  return new Promise((resolve, reject) => {
    fs.readdir(folderPath, (err, files) => {
      if (err) {
        reject(err)
        return
      }
      const directories = files.filter(file =>
        fs.statSync(path.join(folderPath, file)).isDirectory()
      )
      return resolve(directories)
    })
  })
}

function getFilesInFolder(folderPath) {
  return new Promise((resolve, reject) => {
    fs.readdir(folderPath, (err, files) => {
      if (err) {
        reject(err)
        return
      }
      const directories = files.filter(file =>
        fs.statSync(path.join(folderPath, file)).isFile()
      )
      return resolve(directories)
    })
  })
}

function deleteFolder(folderName) {
  return new Promise(async (resolve, reject) => {
    const folderPath = path.join(__dirname, folderName);
    if (!fs.existsSync(folderPath)) {
      return resolve()
    }
    await fs.readdirSync(folderPath).forEach(async (file) => {
      const filePath = path.join(folderPath, file);
      if (fs.lstatSync(filePath).isDirectory()) {
        await deleteFolder(filePath)
      } else {
        fs.unlinkSync(filePath)
      }
    })
    fs.rmdirSync(folderPath)
    return resolve()
  })
  
}

function renameFolder(folderPath, newFolderName) {
  return new Promise((resolve, reject) => {
    const parentPath = path.dirname(folderPath);
    const newPath = path.join(parentPath, newFolderName);

    fs.rename(folderPath, newPath, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve(true);
      }
    });
  });
}

function renameFile(filePath, newFileName) {
  return new Promise((resolve, reject) => {
    const fileDir = path.dirname(filePath);
    const newFilePath = path.join(fileDir, newFileName);
    fs.rename(filePath, newFilePath, (err) => {
      if (err) {
        resolve(false)
      } else {
        resolve(true)
      }
    });
  });
}

function arrayDeleteElem(arr,index){
  let re = []
  for(let i=0;i<arr.length;i++){
      if(i==index){
          continue
      }
      re.push(arr[i])
  }
  return re
}